//////////////////////////////////////////////////////////////////////////////////
//	 Copyright 2011 by Yosef Grabivker, ryuho@homenetworksoft.com
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//////////////////////////////////////////////////////////////////////////////////

#include <wx/wx.h>
#include "logicmanager.h"
#include "wirelessproghw.h"
#include "wirelesswlanprocinthw.h"
#include "wirelesshw.h"

CWirelessHW::CWirelessHW(CLinkGuard& link):m_link(link)
{
}

CWirelessHW::~CWirelessHW(void)
{
}


CWirelessHW* CWirelessHW::CreateInstanse(CLinkGuard& link)
{
	CWirelessHW* pRes(NULL);

	RTSTRING strData = link->SendCmd( wxT("wl txpwr") );

	wxString strWirelessCMDName=wxT("");

	if ( std::string::npos != strData.find("not found") ||
		 std::string::npos != strData.find("No such file") )
	{
		strData = link->SendCmd( wxT("wlctl txpwr") );

		if ( std::string::npos != strData.find("not found") ||
			std::string::npos != strData.find("No such file") )
		{
			//wireless control program was not found
			//check /proc support
			strData = link->ReadFile(CMD_WIRELESS_PROC_STAT);

			if ( !strData.empty() &&
				 std::string::npos == strData.find("No such file") )
			{
				return new CWirelessWLANProcIntHW(link);
			}
		}
		else
		{
			strWirelessCMDName = wxT("wlctl");
		}
	}
	else
	{
		strWirelessCMDName = wxT("wl");
	}

	if ( !strWirelessCMDName.empty() )
	{
		RTSTRING strData = link->ReadFile(CMD_INTERFACE_STAT);
		wxString strInt = ExtractWirelessInt(strData);

		return new CWirelessProgHW(link, strWirelessCMDName, strInt);
	}


	return pRes;
}

wxString CWirelessHW::ExtractWirelessInt(const RTSTRING& strData)
{
	wxString strRes;

	try
	{
		PROCTABLEWITHHEADER tableDev = CLogicManager::ParseTableWithHeaders(strData);

		for (size_t i=0;i<tableDev.rows.size();i++)
		{
			TABLEROW& row = tableDev.rows[i];

			if ( row.empty() ) continue;

			if ( std::string::npos!=row[0].find("wl") )
			{
				strRes = wxString::FromAscii( row[0].c_str() );
				break;
			}
		}
	}
	catch(...)
	{
	}

	return strRes;
}
